import { Subject } from 'rxjs';
import { renderForm, renderButtonList } from './global-tool-form';
export class GlobalTool {
    // 按钮元数据
    items: any[];
    // 元素
    modal: HTMLElement;
    confirmButton: HTMLButtonElement;
    cancelButton: HTMLButtonElement;
    closeButton: HTMLElement;
    buttonContainer: HTMLElement;
    buttons: HTMLElement[];
    selectedList: any[] = [];
    selectedListSubject = new Subject<Array<any>>();
    context: any;
    // 按钮事件
    buttonListEvent: any;
    // 模态框事件
    modalEvent: any;
    // 确定按钮事件
    confirmEvent: any;
    // 取消按钮事件
    closeEvent: any;
    // constructor
    constructor(context: { items?: any[], list?: string[], enableClosedByModal?: boolean }) {
        this.context = context;
        this.items = context.items;
        // 渲染
        this.render();
        this.refreshButton(this.context.items, this.context.list);
        // 绑定事件;
        this.attach();
        // 打开模态框
        this.openModal();
    }

    /**
     * 点击按钮
     * @param e 点击事件
     */
    private clickButtonList(e) {
        if (e.target['nodeName'].toLowerCase() === 'button') {
            const self = e.target;
            if (self['classList'].contains('disabled')) {
                return;
            }
            if (self['classList'].contains('text-white')) {
                this.blurButton(self);
            } else {
                this.focusButton(self);
            }
        }
    }

    private clickConfirm() {
        // 收集选中的按钮
        const selectedButtons = this.modal.querySelectorAll('.text-white');
        this.selectedList = Array.from(selectedButtons).map(btn => btn.id);
        // 获取选择的按钮组
        this.selectedListSubject.next(this.selectedList);
        // 关闭modal
        this.close();
    }

    /**
     * 关闭模态框
     */
    private closeModal() {
        if (this.modal) {
            this.modal.classList.remove('d-block');
            this.modal.classList.add('d-none');
        }
    }

    /**
     * 关闭所有
     */
    private close() {
        // 所有元素恢复原状
        this.buttons.forEach(btn => {
            if (btn.classList.contains('text-white')) {
                this.blurButton(btn);
            }
        });
        // 解绑所有事件
        this.detach();
        this.closeModal();
    }
    /**
     * 添加绑定事件
     * @param el 绑定元素
     * @param eventType 事件类型
     * @param event 监听器
     */
    private addEventListener(el: HTMLElement, eventType: string, event: any) {
        if (el.addEventListener) {
            el.addEventListener(eventType, event);
        }
    }

    /**
     * 移除事件
     * @param el 绑定元素
     * @param eventType 事件类型
     * @param event 事件
     */
    private removeEventListener(el: HTMLElement, eventType: string, event: any) {
        if (event) {
            if (el.removeEventListener) {
                el.removeEventListener(eventType, event);
            }
        }
    }

    /**
     * 聚焦
     * @param button 按钮元素
     */
    private focusButton(button: any) {
        button.classList.add('bg-primary', 'text-white');
    }

    /**
     * 失去焦点
     * @param button 按钮元素
     */
    private blurButton(button: any) {
        button.classList.remove('bg-primary', 'text-white');
    }

    /**
     * 打开模态框
     */
    openModal() {
        if (!this.modal) {
            return;
        }
        this.modal.classList.remove('d-none');
        this.modal.classList.add('d-block');
    }

    rebuild(context) {
        new Promise((resolve, reject) => {
            this.render();
            // 首次加载  刷新
            this.refreshButton(context.items, context.list);
            resolve('a');
        }).then(() => {
            // 绑定事件;
            this.attach();
            // 打开模态框
            this.openModal();
        });
    }

    refreshButton(items, list) {
        this.buttonContainer.innerHTML = renderButtonList(items, list).join('');
    }

    render() {
        // 创建模态框
        this.modal = document.body.querySelector('#global-tool-modal');
        if (!this.modal) {
            const ctx = {
                items: this.items,
                title: '选择按钮',
                disabledList: this.context.list
            };
            this.modal = renderForm(ctx);
        }
        this.initElement();
    }

    // 获取节点元素
    initElement() {
        // 初始化确定  取消按钮
        this.confirmButton = this.modal.querySelector('[ref="global-modal__confirm"]');
        this.cancelButton = this.modal.querySelector('[ref="global-modal__cancel"]');
        this.closeButton = this.modal.querySelector('[ref="global-modal__close"]');
        this.buttonContainer = this.modal.querySelector('[ref="global-modal__list"]');
        // this.buttons = [].slice.call(this.buttonContainer.querySelectorAll('button'));
        this.buttons = Array.prototype.slice.call(this.buttonContainer.querySelectorAll('button'));
    }

    /**
     * 绑定事件
     */
    attach() {
        // 绑定确定按钮事件
        this.confirmEvent = this.bindEvent(this.clickConfirm);
        this.addEventListener(this.confirmButton, 'click', this.confirmEvent);

        // 绑定工具栏按钮事件  事件委托
        this.buttonListEvent = this.bindEvent(this.clickButtonList);
        this.addEventListener(this.buttonContainer, 'click', this.buttonListEvent);

        this.closeEvent = this.bindEvent(this.close);
        // 绑定模态框事件
        if (this.context.enableClosedByModal) {
            this.addEventListener(this.modal, 'click', this.closeEvent);
        }
        // 绑定取消事件
        this.addEventListener(this.cancelButton, 'click', this.closeEvent);
        // 绑定右上角关闭事件
        this.addEventListener(this.closeButton, 'click', this.closeEvent);
    }

    /**
     * 解绑所有事件
     */
    detach() {
        this.removeEventListener(this.confirmButton, 'click', this.confirmEvent);
        this.removeEventListener(this.buttonContainer, 'click', this.buttonListEvent);
        this.removeEventListener(this.cancelButton, 'click', this.closeEvent);
        this.removeEventListener(this.closeButton, 'click', this.closeEvent);
        this.removeEventListener(this.cancelButton, 'click', this.closeEvent);
        if (this.context.enableClosedByModal) {
            this.removeEventListener(this.modal, 'click', this.closeEvent);
        }
        this.confirmEvent = null;
        this.buttonListEvent = null;
        this.closeEvent = null;
    }

    /**
     * 封装绑定事件  用于统一阻止冒泡  方便解绑事件
     * @param eventKey 事件标识
     * @param fn 监听函数
     * @param option 配置项
     */
    bindEvent<T>(fn: (value?: any) => any, param = [], option = { stopPropagation: true }): T {
        const lisenter = (e) => {
            if (option && option.stopPropagation) {
                e.stopPropagation();
            }
            fn.call(this, ...[...param, e]);
        };
        return lisenter.bind(this);
    }

    /**
     * 订阅对象
     */
    observeSelected$() {
        return this.selectedListSubject;
    }




}
